package com.senseauto.ffmpegrecordvideo;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.util.Size;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.Arrays;

/**
 * StartActivity
 * 主要用来权限申请的界面
 */
public class StartActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = StartActivity.class.getSimpleName();
    private static final int MESSAGE_DMS_FAIL = 0;
    private static final int MESSAGE_DMS_SUCCESS = 1;

    private final String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.INTERNET,
            Manifest.permission.CAMERA};

    private boolean permissionGetted;

    private int permissionState;

    private Spinner videoRecordList;

    private EditText etCameraId, etWidth, etHeight;

    private ActivityResultLauncher<String[]> permissionRequest = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), granteds -> {
        boolean parsed = true;
        Log.i(TAG, "permission result : class->" + granteds.getClass());
        for (String key : granteds.keySet()) {
            parsed &= granteds.get(key);
        }
        permissionGetted = parsed;
        if (parsed && permissionState == 2) {
        }
    });


    private static boolean checkPermission(Context context) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context.getApplicationContext(), "please open camera permission of this application", Toast.LENGTH_SHORT).show();
            return false;
        } else if (ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context, "please open write/read sdcard permission of this application", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);
        checkPermission(this);
        initView();
    }
    protected void initView() {
        setContentView(R.layout.activity_start);
        requestPermission();
        etCameraId = findViewById(R.id.dmsID);
        etWidth = findViewById(R.id.tvWidth);
        etHeight = findViewById(R.id.tvHeight);

        findViewById(R.id.btn_camera1).setOnClickListener(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: ");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e(TAG, "onRequestPermissionsResult: rc=" + requestCode
                + "\n" + Arrays.toString(permissions) + "\n" + Arrays.toString(grantResults));
        boolean enable = true;
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                enable = false;
                break;
            }
        }
        permissionGetted = enable;
        if (enable && requestCode == 2) {
        }
        if(permissionGetted){
            displayCameraInfo();
        }
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int REQUEST_CODE_CONTACT = 1;
            for (String str : permissions) {
                if (ContextCompat.checkSelfPermission(this, str) != PackageManager.PERMISSION_GRANTED) {
                    permissionState = 1;
                    permissionRequest.launch(permissions);
//                    ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
            permissionGetted = true;
            displayCameraInfo();
        } else {
            if (!checkPermission(getApplicationContext())) {
                new AlertDialog.Builder(this)
                        .setTitle("Tips")
                        .setMessage("Your app is missing some privileges,please go to authorize")
                        .setPositiveButton("setting", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                finish();
                            }
                        }).show();
            } else {
                permissionGetted = true;
                displayCameraInfo();
            }
        }
    }
    private void displayCameraInfo(){
        CameraManager cameraManager = (CameraManager) AutoApplication.getContext().getSystemService(Context.CAMERA_SERVICE);
        try {
            String[] cameraIds = cameraManager.getCameraIdList();
            Log.e(TAG, "cameraIds.length=" + cameraIds.length);
            for (String cameraId : cameraIds) {
                CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);
                StreamConfigurationMap configMap = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                Size[] sizes = configMap.getOutputSizes(SurfaceTexture.class);
                Log.e(TAG, "cameraId=" + cameraId);
                // 打印输出所有这个摄像头支持分辨率信息
                for (Size size : sizes) {
                    Log.e(TAG, "getCameraInfo() Camera " + cameraId + " supported resolution: " + size.getWidth() + "x" + size.getHeight());
                }
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {


            case R.id.btn_camera1: {
                String cameraIdStr = etCameraId.getText().toString().trim();
                String widthStr = etWidth.getText().toString().trim();
                String heightStr = etHeight.getText().toString().trim();
                int width = -1;
                int height = -1;
                if (!TextUtils.isEmpty(widthStr) && TextUtils.isDigitsOnly(widthStr)) {
                    width = Integer.parseInt(widthStr);
                }
                if (!TextUtils.isEmpty(heightStr) && TextUtils.isDigitsOnly(heightStr)) {
                    height = Integer.parseInt(heightStr);
                }
                int cameraId=0;
                if (!TextUtils.isEmpty(cameraIdStr)) {
                    cameraId = Integer.parseInt(cameraIdStr);
                }
                intent=  new Intent(this, Camera1Activity.class);
                intent.putExtra("dmsCameraID", cameraId);
                intent.putExtra("width", width);
                intent.putExtra("height", height);
                Log.e(TAG, "cameraId="+cameraId+" width="+width+" height="+height);
                startActivity(intent);
            }
                break;
            default:
                break;
        }
    }


    public void ExitClick(View view) {
        new AlertDialog.Builder(this).setMessage("Exit the program?").setTitle("Tips")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                        System.exit(0);
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        return super.onKeyDown(keyCode, event);
    }
}
